# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# 建立者:        潘炎珍  
# Name:         hw01
# Description:
# Author:       98745
# Date:         2019/4/20
#-------------------------------------------------------------------------------

import json
import dicttoxml
from xml.dom.minidom import parseString

class Split:
    def get_dict(self):
        try:
            f=open('./file.json','r',encoding='utf-8')
            jsonstr=f.read()
            dict=json.loads(jsonstr)#将json字符串转换为字典
            print(dict)
            f.close()
            return dict
        except Exception as e:
            print(e)

    def get_info(self,dict):
        try:
            s='{:^10} {:^10} {:^10} {:^10} {:^10}'.format('thd_name','id','title','t_id','orderno')
            self.write_file(s)
            for item in dict['data']:
                thd_name=item['thd_name']
                # self.write_file(thd_name)
                self.get_product(thd_name,item['product'])
        except Exception as e:
            print(e)

    def get_product(self,thd_name,product):
        try:
            for item in product:
                id=item['id']
                title=item['title']
                t_id=item['t_id']
                orderno=item['orderno']
                data='{:^10} {:^10} {:^10} {:^10} {:^10}'.format(thd_name,id,title,t_id,orderno)
                self.write_file(data)
        except Exception as e:
            print(e)

    def write_file(self,data):
        try:
            f=open('./file.txt','a+',encoding='utf-8')
            f.write(data+'\n')
            f.close()
        except Exception as e:
            print(e)


if __name__=="__main__":
    try:
        split=Split()
        dict=split.get_dict()
        split.get_info(dict)
    except Exception as e:
        print(e)

    #将字典转换为xml文件
    # bxml=dicttoxml.dicttoxml(dict,custom_root='file')
    # xml=bxml.decode('utf-8')
    # dom=parseString(xml)
    # prettydom=dom.toprettyxml(indent='    ')
    # f1=open('./dicttoxml.xml','w',encoding='utf-8')
    # f1.write(prettydom)
    # f1.close()






